<template>
    <div
        class="statement-contnair"
        v-loading="isLoading"
        element-loading-background="rgba(250, 250, 250, 0.7)"
    >
        <cardComponent pageTitle="账单分期详情">
            <template slot="cardBody">
                <el-form
                    ref="statementformRef"
                    :rules="statementRules"
                    :model="statementForm"
                    label-width="120px"
                    size="small"
                >
                    <el-row>
                        <el-col :span="7">
                            <el-form-item label="账户是类别 : ">
                                <el-input disabled v-model="statementForm.CATEGORY"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="主卡卡号 : ">
                                <el-input
                                    disabled
                                    v-model="statementForm.CARDNBR"
                                    style="width: 100%;"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="手续收取方式 : " prop="CREDNO">
                                <el-select
                                    v-model="statementForm.CREDNO"
                                    @change="onQry('statementformRef')"
                                    style="width: 100%;"
                                >
                                    <el-option label="一次性收取" value="0002"></el-option>
                                    <el-option label="分期收取" value="0022"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="3">
                            <el-form-item size="small" label-width="25px">
                                <el-button
                                    type="primary"
                                    size="small"
                                    @click="onQry('statementformRef')"
                                >查 询</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <!-- </el-card> -->

                <!-- 账单分期详情 -->
                <el-card class="trailTable" shadow="never" v-if="showQry">
                    <div slot="headerss">
                        <span>账单分期详情</span>
                        <el-button
                            style="float: right; padding: 3px 20px;"
                            type="text"
                            @click="showQry=false"
                        >关 闭</el-button>
                    </div>
                    <div>
                        <el-table
                            :data="trailTable"
                            style="width: 100%; margin: 0 auto;"
                            border
                            stripe
                            class="heard-bg business_table"
                        >
                            <el-table-column prop="CREDNO_1" label="信用计划编号"></el-table-column>
                            <el-table-column prop="UNBALFRE" label="截止昨日未还消费余额"></el-table-column>
                            <el-table-column prop="SMPPAMT" label="参考申请金额"></el-table-column>
                            <el-table-column prop="OPENAMT" label="本期账单金额"></el-table-column>
                        </el-table>
                        <table></table>
                        <el-divider content-position="center">费用试算表</el-divider>
                        <el-form
                            :inline="true"
                            :rules="formInlineRules"
                            ref="formInlineRef"
                            :model="formInline"
                            size="small"
                            class="demo-form-inline"
                        >
                            <el-form-item label="分期金额 : " prop="AMT">
                                <el-input
                                    @change="onChanger('formInlineRef')"
                                    v-model="formInline.AMT"
                                    placeholder="分期金额"
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="选择分期期数 : " prop="NBRMTHS">
                                <el-select
                                    v-model="formInline.NBRMTHS"
                                    placeholder="选择分期期数"
                                    @change="onChanger('formInlineRef')"
                                >
                                    <el-option
                                        v-for="(item, index) in instalmentNoList"
                                        :key="index"
                                        :label="item.label"
                                        :value="item.nbrMths"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="差额 : ">
                                <el-input maxlength="8" :value="balance.toFixed(2)" disabled></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button
                                    type="primary"
                                    size="small"
                                    @click="onSubmit('formInlineRef')"
                                    v-preventReClick
                                >申 请</el-button>
                            </el-form-item>
                        </el-form>
                        <el-table
                            :data="trailAMT"
                            style="width: 100%; margin-top: 10px;"
                            border
                            stripe
                            class="heard-bg business_table"
                        >
                            <el-table-column prop="instalAmts" label="每期分摊本金"></el-table-column>
                            <el-table-column prop="firstAmts" label="首期还款额"></el-table-column>
                            <el-table-column prop="FEEAMT" label="分期总手续费"></el-table-column>
                            <el-table-column prop="allcountfee" label="本金+手续费总计"></el-table-column>
                            <el-table-column prop="MPIRR" label="年化利率"></el-table-column>
                        </el-table>
                        <div v-if="showexistStatement">
                            <el-divider content-position="center">已申请账单分期信息</el-divider>
                            <el-table
                                :data="existStatementTable"
                                style="width: 100%; margin-top: 10px;"
                                border
                                stripe
                                class="heard-bg business_table"
                            >
                                <el-table-column prop="CREDNO_1" label="信用计划编号"></el-table-column>
                                <el-table-column prop="AMT" label="分期金额"></el-table-column>
                                <el-table-column prop="MONTHNBR" label="	分期期数"></el-table-column>
                                <el-table-column prop="INSTALAMT" label="每月还款额"></el-table-column>
                                <el-table-column prop="UNSTM" label="截止昨日未还账单余额"></el-table-column>
                            </el-table>
                        </div>
                    </div>
                </el-card>

                <!-- 申请成功窗口 -->
                <ConfirmWindow
                    v-if="showsuccess"
                    @isShow="close"
                    :dataList="statementsuccess"
                    :title="'帐单分期申请成功,请勿重复申请！'"
                />
            </template>
        </cardComponent>
    </div>
</template>

<script>
import { mapState } from 'vuex';
import cardComponent from '@/components/cardComponent/cardComponent.vue';
import ConfirmWindow from '@/components/ConfirmWindow/ConfirmWindow.vue';
import { getInstalmentList, getDictMappingValue } from '@/utils/Common';
import { get_3xxx, get_4xxx } from '@/apis/getAPIClass';
import { setNumber, tbBudgetRequisi } from '@/utils/Object';
import { RegConfig } from '@/utils/RegConfig';

export default {
    components: {
        ConfirmWindow,
        cardComponent,
    },
    name: 'statement',
    data() {
        return {
            statementForm: {
                CATEGORY: '',
                CARDNBR: '',
                CREDNO: '0002',
            },
            showsuccess: false,
            showexistStatement: false,
            statementsuccess: [],
            statementRules: {
                CREDNO: [
                    {
                        required: true,
                        message: '请选择手续收取方式！',
                        trigger: 'change',
                    },
                ],
            },
            formInlineRules: {
                AMT: [
                    {
                        required: true,
                        message: '请输入分期金额！',
                        trigger: 'blur',
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (parseFloat(value) != value * 1) {
                                callback(new Error('请输入数字！'));
                            } else {
                                callback();
                            }
                        },
                        trigger: 'blur',
                    },
                    {
                        validator: (rule, value, callback) => {
                            // if (this.flag) {
                            if (value < 200 || value > this.trailTable[0].SMPPAMT) {
                                callback(new Error('需介于200和参考申请金额之间的数值！'));
                            } else {
                                callback();
                            }
                            // } else {
                            //   callback();
                            // }
                        },
                        trigger: 'blur',
                    },
                ],
                NBRMTHS: [
                    {
                        required: true,
                        message: '请选择分期期数！',
                        trigger: 'change',
                    },
                ],
            },
            instalmentNoList: [],
            trailTable: [
                {
                    CREDNO: '', // 4052
                    UNBALFRE: '', // 4052
                    UNSTM: '',
                    SMPPAMT: '', // 4052
                    OPENAMT: '', // 3053
                    FEEAMT: '',
                },
            ],
            trailAMT: [
                {
                    firstAmts: '' || 0, // 4052
                    instalAmts: '' || 0, // 4052
                    FEEAMT: '' || 0, // 4052
                    allcountfee: '' || 0, // 3053
                    MPIRR: '' || 0,
                },
            ],
            existStatementTable: [
                {
                    firstAmts: '' || 0, // 4052
                    instalAmts: '' || 0, // 4052
                    FEEAMT: '' || 0, // 4052
                    allcountfee: '' || 0, // 3053
                    MPIRR: '' || 0,
                },
            ],
            formInline: {
                AMT: '',
                NBRMTHS: '',
            },
            showQry: false,
            isLoading: false,
            timeID: '',
            flag: false,
        };
    },
    async mounted() {
        // 获取账户类别
        const MY_CATEGORY = await getDictMappingValue('CATE', this.cardInfo_3004.CATEGORY, this) || this.cardInfo_3004.CATEGORY;

        this.statementForm.CATEGORY = MY_CATEGORY;
        this.onLoadstatementOBJ();
    },
    computed: {
        ...mapState({
            defaultParams: state => state.common.defaultParams, // 接口默认参数
            cardInfo_3004: state => state.common.cardInfo_3004,
            cardList_3601: state => state.common.cardList_3601,
            pinFlag: state => state.common.pinFlag, // 是否密码检查标志
        }),
        // 计算差额
        balance() {
            return (
                parseFloat(this.trailTable[0].OPENAMT || 0)
                - parseFloat(this.formInline.AMT || 0)
            );
        },
    },
    methods: {
        async onLoadstatementOBJ() {
            this.statementForm.CARDNBR = this.cardInfo_3004.CARDNO;
            // await this.onQry('statementformRef')
        },
        // 3053  4052 账单分期查询
        async onQry(ref) {
            this.$refs[ref].validate(async (valid) => {
                if (!valid) return false;

                this.isLoading = true;
                // 3053 配置请求头
                const appBody_3053 = {
                    CARDNBR: this.statementForm.CARDNBR,
                    COVERTTY: 0, // 汇率种类
                    PINFLAG: this.pinFlag,
                };
                // 发送_3053 4052请求
                const result_3053 = await get_3xxx(
                    '3053',
                    '账单分期查询',
                    appBody_3053,
                    this,
                    false,
                );
                const result_4052 = await this.get_4052(
                    '账单分期查询',
                    0,
                    0,
                    3,
                    0,
                    0,
                    '156',
                    this.statementForm.CREDNO,
                );
                console.log(this.statementForm.CREDNO, 'result_4052');
                if (!result_4052 || !result_3053) return false;
                const res_3053 = result_3053.body.appBody;
                const res_4052 = result_4052.body.appBody;
                // 清空试算列表
                this.formInline.AMT = '';
                this.formInline.NBRMTHS = '';
                res_4052.CREDNO = setNumber(res_4052.CREDNO, 4, false);
                // 获得信用信息
                console.log(res_4052.CREDNO, 'res_4052.CREDNO');
                try {
                    // this.showQry = true;
                    const nemea = await getDictMappingValue('1082', res_4052.CREDNO, this);
                    console.log(nemea, 'nemea');
                    res_4052.CREDNO_1 = `${res_4052.CREDNO} - ${nemea}`;
                    // 分期期数
                    this.instalmentNoList = await getInstalmentList(
                        res_4052.CREDNO,
                        this,
                    );
                    console.log(this.instalmentNoList, 'this.instalmentNoList');
                    this.formInline.NBRMTHS = this.instalmentNoList[0].nbrMths;
                    // console.log(this.instalmentNoList[0].nbrMths);
                    // if (this.statementForm.CREDNO == "0002") {
                    //   this.formInline.NBRMTHS = "3";
                    // } else {
                    //   this.formInline.NBRMTHS = "6";
                    // }
                } catch (error) { console.warn(error, '未获取到分期列表'); }

                // res_4052.CREDNO;
                // 成功之后当前显示
                this.showQry = true;
                this.trailTable = [{ ...res_4052, ...res_3053 }];
                console.log(this.trailTable, 'this.trailTable');
                // 判断是否存在已分企账单展示
                this.showexistStatement = false;
                this.existStatementTable = [];
                if (res_4052.AMT && res_4052.MONTHNBR && res_4052.INSTALAMT) {
                    this.showexistStatement = true;
                    // this.existStatementTable[0].CREDNO_1 = nemea
                    this.existStatementTable = [{ ...res_4052, CREDNO_1: nemea }];
                }

                this.isLoading = false;

                this.showQry = true;
            });
        },
        //  4052 账单分期申请
        async onSubmit(ref) {
            this.flag = true;
            this.$refs[ref].validate(async (valid) => {
                if (!valid) return false;

                // 再次确定是否申请
                const confirmResult = await this.$confirm(
                    '此操作将进行账单分期申请, 是否继续?',
                    '账单分期申请提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        customClass: 'warning',
                        type: 'warning',
                    },
                ).catch(err => err);
                if (confirmResult !== 'confirm') return this.$message.info('已取消账单分期申请');

                this.isLoading = true;
                const result_4052 = await this.get_4052(
                    '账单分期申请',
                    0,
                    0,
                    0,
                    0,
                    0,
                    '156',
                    this.statementForm.CREDNO,
                    this.formInline.NBRMTHS,
                    this.formInline.AMT,
                );
                if (!result_4052) return false;
                const res = result_4052.body.appBody;
                // 配置成功之后展示的数据
                this.statementsuccess = [
                    { keys: '主卡卡号 : ', values: res.CARDNBR },
                    { keys: '分期金额 : ', values: res.AMT },
                    { keys: '每月还款额 : ', values: res.INSTALAMT },
                    { keys: '分期期数 : ', values: res.MONTHNBR },
                    { keys: '总手续费 : ', values: res.FEEAMT },
                ];
                // console.log(result_4094);
                // 发送新增分期申请记录 tbBudgetRequisi
                const tbBudgetRequisiData = JSON.parse(JSON.stringify(tbBudgetRequisi));
                tbBudgetRequisiData.agentid = this.defaultParams.body.appHead.opeNo;
                tbBudgetRequisiData.allcountfee = res.FEEAMT;
                tbBudgetRequisiData.banknum = this.defaultParams.body.appHead.bnknbr;
                tbBudgetRequisiData.budgettype = res.OPERTP;
                tbBudgetRequisiData.custid = this.cardInfo_3004.CUSTID || '无';
                tbBudgetRequisiData.custname = this.cardInfo_3004.NAME;
                tbBudgetRequisiData.custno = res.CARDNBR;
                tbBudgetRequisiData.instalamt = res.AMT;
                tbBudgetRequisiData.jzrate = res.MPFEECD;
                tbBudgetRequisiData.planno = res.CREDNO;
                tbBudgetRequisiData.retcode = '000000';
                tbBudgetRequisiData.monthnbr = res.MONTHNBR;
                tbBudgetRequisiData.smppamt = res.SMPPAMT;

                console.log(tbBudgetRequisiData);
                try {
                    const resss = await this.$post.businessStatistics.addTbBudgetRe(
                        tbBudgetRequisiData,
                    );
                    console.log(resss);
                } catch (error) {
                    console.warn(error);
                }

                this.$refs.formInlineRef.resetFields();
                this.showsuccess = true;
            });
        },
        // 请求 4052
        async get_4052(
            masg,
            COVERTTY,
            PINFLAG,
            OPERTP,
            PRMCHK,
            CLSCHK,
            CURRNUM,
            CREDNO,
            NBRMTHS = '',
            AMT = '',
        ) {
            // 4052 配置请求头
            const appBody_4052 = {
                CARDNBR: this.statementForm.CARDNBR,
                COVERTTY, // 汇率种类
                PINFLAG,
                OPERTP, // 操作类型 0－申请 1－撤销 2—查询 3—上期账单信息查询 4-预申请
                PRMCHK,
                CLSCHK,
                CURRNUM,
                CREDNO,
                NBRMTHS, // 分期期数
                AMT: setNumber(AMT, 12), // 分期金额
            };

            const result_4052 = await get_4xxx('4052', masg, appBody_4052, this);
            if (!result_4052) return false;
            // if (OPERTP == 0) {
            //   this.$alert(`${masg}成功,请勿重复提交 !`, `${masg}提示！`, {
            //     confirmButtonText: "确定",
            //     center: true,
            //     type: "success ",
            //     showClose: false
            //   });
            // }
            return result_4052;
        },
        // 4089 試算請求
        onChanger(ref) {
            this.flag = false;
            this.$refs[ref].validate(async (valid) => {
                if (!valid) return false;
                // if (!this.formInline.AMT || !this.formInline.NBRMTHS) return false;
                this.get_4089();
            });
        },
        async get_4089() {
            this.isLoading = true;
            // 4089 配置请求头
            const appBody_4089 = {
                CARDNBR: this.statementForm.CARDNBR,
                OPT: 1,
                PINFLAG: this.pinFlag,
                CREDNO: this.statementForm.CREDNO,
                NBRMTHS: this.formInline.NBRMTHS, // 分期期数
                BILLAMT: setNumber(this.formInline.AMT, 12),
                CURRNUM: '156',
            };
            console.log(appBody_4089);
            const result_4089 = await get_3xxx(
                '4089',
                '账单分期',
                appBody_4089,
                this,
            );
            console.log(result_4089);
            if (!result_4089) return false;
            // 成功之后当前显示
            const feeInstl = result_4089.body.appBody.FEEINSTL; // 月手续费
            const instalAmt = result_4089.body.appBody.INSTALAMT; // 月还款额
            const feeAmt = result_4089.body.appBody.FEEAMT; // 总手续费
            const feePcnt = result_4089.body.appBody.FEEPCNT; // 利率
            const feeFlag = result_4089.body.appBody.FEEFLAG; // 0：一次性收取 1：分期收取
            const mp_irr = result_4089.body.appBody.MPIRR; // 年化利率

            const amount = this.formInline.AMT;
            const mon = parseInt(this.formInline.NBRMTHS);
            // 首期还款额 = 本金 / 期数 + 总手续费
            const firstAmts = amount / mon + feeAmt;

            // 总还款额 = 总手续费 + 本金
            const allcountfee = feeAmt + amount * 1;
            console.log(feeAmt, amount);

            // 本金 = 本金 / 期数
            let corpus = 0;
            corpus = amount / mon;
            // if (feeFlag == 0) {
            // feeAmt = feeAmt * 0.75;
            // firstAmts = (firstAmts - corpus) * 0.75 + corpus;
            // allcountfee = allcountfee - feeAmt / 3;
            // }
            // 月还款额 = 本金 + 月手续费
            this.trailAMT[0].instalAmts = (corpus * 1).toFixed(2);
            // this.trailAMT[0].instalAmts = ((corpus + feeInstl) * 1).toFixed(2);
            this.trailAMT[0].allcountfee = (allcountfee * 1).toFixed(2);
            // 首期还款额 = 本金 / 期数 + 总手续费
            this.trailAMT[0].firstAmts = (firstAmts * 1).toFixed(2);
            this.trailAMT[0].FEEAMT = (feeAmt * 1).toFixed(2);
            this.trailAMT[0].MPIRR = mp_irr;

            this.isLoading = false;
        },
        // 将组件返回的false赋值给当前
        close(data) {
            this.showsuccess = data;
        },
    },
};
</script>

<style  scoped lang="scss">
.statement-contnair {
    /deep/.el-card__header {
        padding: 8px !important;
    }
    /deep/.trailTable {
        .el-card__body {
            // padding: 0!important;
        }
    }
    .el-form {
        //   text-align: left;
        // margin: 0 auto;
        // width: 500px;
        .el-form-item {
            text-align: left;

            // margin-bottom: 0px;
        }
    }
    .el-select {
        width: 100%;
        // margin-bottom: 15px;
    }

    .el-form-item {
        text-align: left;
    }
}
</style>
